<?php
class Codetool_AuthenticationController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$this->_redirect("cms/");
	}
	private function mahoa($string)
	{
		return md5(sha1($string));
	}
	public function changepassAction()
	{
		if (!Zend_Auth::getInstance()->hasIdentity())
		{
			$this->_redirect("authentication/login");
		}
		$this->_helper->layout()->disablelayout();
		if ($this->_request->isPost())
		{
			$oldPass = $this->_request->getParam("oldpass");
			$newPass = $this->_request->getParam("newpass");
			$xdPass = $this->_request->getParam("xacdinh");
			$message = null;
			if ($newPass != $xdPass)
			{
				$message[] = "Xác nhận mật khẩu không đúng";
			}
			else 
			{
				$userOb = new Henry_Users();
				$authStorage = Zend_Auth::getInstance()->getStorage();
				$userdata = $authStorage->read();
				$username = $userdata->user;
				if ($userOb->isPassOk($username, $oldPass))
				{
					if ($userOb->changePass($username, $newPass))
					{
						$message[] = "Thành Công";
						$this->view->flag = true;
						Zend_Auth::getInstance()->clearIdentity();
					}
					else 
					{
						$message[] = "Đổi mật khẩu không thành công";
					}
				}
				else 
				{
					$message[] = "Mật khẩu cũ không đúng";
				}
			}
			$this->view->message = $message; 
		}
	}
	public function loginAction()
	{
		if (Zend_Auth::getInstance()->hasIdentity())
		{
			$this->_redirect("cms/index");
		}
		$this->_helper->layout()->disablelayout();
		$request = $this->_request;
		if ($request->isPost())
		{
			$authAdapter = $this->getAuthAdapter();
			$user = trim($request->getParam("user"));
			$pass = $this->mahoa(trim($request->getParam("pass")));
			$authAdapter->setIdentity($user);
			$authAdapter->setCredential($pass);
			$auth = Zend_Auth::getInstance();
			$result = $auth->authenticate($authAdapter);
			if ($result->isValid())
			{
				$identity = $authAdapter->getResultRowObject();
				$authStorage = $auth->getStorage();
				$authStorage->write($identity);
				$this->_redirect("cms/index");
			}
			else 
			{
				$this->view->message = "Sai user hoặc pass";
			}
		}
	}
	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect("cms/authentication/login");
	}
	private function getAuthAdapter()
	{
		$user = new Henry_Users();
		$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
		$authAdapter->setTableName($user->info(Henry_Users::NAME))
					->setIdentityColumn("user")
					->setCredentialColumn("password");
		return $authAdapter;			
	}
}